package com.wu.leetcode.leetcode463;

/**
 *
 */
class Solution {
    public int islandPerimeter(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    return dfs(grid, i, j);
                }
            }
        }
        return 0;
    }

    private int dfs(int[][] grid, int x, int y) {
        if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) {
            return 1;
        }
        if (grid[x][y] != 1) {
            return 0;
        }
        grid[x][y] = 2;
        return dfs(grid, x + 1, y) +
                dfs(grid, x - 1, y) +
                dfs(grid, x, y + 1) +
                dfs(grid, x, y - 1);
    }
}